package web.weibo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HelloWorldController {
    public static void log(String format, Object... args) {
        System.out.println(String.format(format, args));
    }

    @GetMapping("/routeDemo1")
    // 会自动从 reqeust 里面找名字为 name 的参数
    public ModelAndView routeDemo1(String name) {
        ModelAndView mv = new ModelAndView("routeDemo1");
        mv.addObject("name", name);
        return mv;
    }

    @GetMapping("/routeDemo2")
    public ModelAndView routeDemo2(String title) {
        ModelAndView mv = new ModelAndView("routeDemo2");
        mv.addObject("title", title);
        return mv;
    }

    // @GetMapping("/routeDemo3")
    // public ModelAndView routeDemo3(String title, String content) {
    //     if (title == null) {
    //         title = "";
    //     }
    //     if (content == null) {
    //         content = "";
    //     }
    //     ModelAndView mv = new ModelAndView("routeDemo3");
    //     mv.addObject("title", title);
    //     mv.addObject("content", content);
    //     return mv;
    // }

    @GetMapping("/routeDemo3" )
    public ModelAndView routeDemo3( @RequestParam(value = "title", required = false, defaultValue = "") String title,
                                    @RequestParam(value = "content", required = false, defaultValue = "") String content) {
        ModelAndView mv = new ModelAndView("routeDemo3");
        mv.addObject("title", title);
        mv.addObject("content", content);
        return mv;
    }

    @PostMapping("/routeDemo3/post")
    public String routeDemo3Post(String demo_input) {
        ModelAndView mv = new ModelAndView("routeDemo3");
        mv.addObject("demo_input", demo_input);
        log("輸出：%s", demo_input);
        // return new ModelAndView("redirect:/routeDemo3");
        return "redirect:/routeDemo3";
    }
}